<?php
// +----------------------------------------------------------------------
// | 有小象汇 自研正版源码 赋能开发者
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 http://www.uxphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 有小象汇并不是自由软件，未经许可不能去掉有小象汇相关版权
// +----------------------------------------------------------------------
// | Author:  有小象汇
// +----------------------------------------------------------------------

namespace app\services\car;


use app\dao\car\CarOrderTakeDao;
use app\model\car\CarOccupyTime;
use app\model\car\CarOrder;
use app\model\car\CarOrderTake;
use app\model\car\CarType;
use app\services\BaseServices;
use think\exception\ValidateException;

/**
 * Class CarOrderTakeServices
 * @package app\services\car
 */
class CarOrderTakeServices extends BaseServices
{
    public function __construct(CarOrderTakeDao $dao)
    {
        $this->dao = $dao;
    }
    // 生成取车单号
    public function getTakeNo(){
        $date = date('YmdHis',time()).rand(10,99);
        return 'QC'.$date;
    }

    /**
     * 创建取车信息
     * @param $data
     * @param $op_user
     * @param $op_user_type
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function accomplisTake($data=[],$op_user=[],$op_user_type=''){
        $orderInfo = CarOrder::where('id',$data['order_id'])->find();
        $orderInfo = $orderInfo ? $orderInfo->toArray() : [];
        if(!$orderInfo) throw new ValidateException('未查询到订单');
        $car_type = CarType::find($orderInfo['type_id'])->toArray();
        if(!is_timestamp($data['take_time'])){
            $data['take_time'] = strtotime($data['take_time']);
        }
        // 查找车辆信息
        $insert = [
            'car_id'=>$data['car_id'],
            'car_no'=>$data['car_no'],
            'take_staff_id'=> $op_user['id'] ?? 0,
            'take_time'=>$data['take_time'],
            'take_pic_oil'=>$data['take_pic_oil'],
            'take_injury_pic'=>json_encode($data['take_injury_pic']),
            'take_contract_pic'=>json_encode($data['take_contract_pic']),
            'take_video'=>$data['take_video'],
            'old_type_id'=>$data['old_type_id'],
            'new_type_id'=>$data['new_type_id'],
            'illegal_deposit'=>$car_type['illegal_deposit'],
            'deposit'=>$car_type['deposit'],
            'all_deposit_fee'=>bcadd($car_type['illegal_deposit'],$car_type['deposit'],2),
            'integral_fee'=>$data['integral_fee'],
            'deposit_fee'=>bcadd($car_type['illegal_deposit'],$car_type['deposit'],2),
            'sign_post_time'=>$data['sign_post_time'],
            'sign_notify_time'=>$data['sign_notify_time'],
            'take_km' => $data['take_km']
        ];
        $this->transaction(function () use ($insert,$data,$orderInfo,$op_user,$op_user_type){
            if($orderInfo['take_id']){ // 修改
                $takeInfo = CarOrderTake::find($orderInfo['take_id']);
                $takeInfo = $takeInfo ? $takeInfo->toArray() : [];
                if(!$res = CarOrderTake::where('id',$orderInfo['take_id'])->update($insert)) throw new ValidateException('提交失败');
                CarOrder::where('id',$data['order_id'])->update(['status'=>20]);
                if($takeInfo){
                    // 如果车牌号与下单时不同且是内部车判定员工换车
                    if($takeInfo['car_no'] != $insert['car_no'] && $data['car_id']){
                        //修改订单表的车辆车牌；id
                        CarOrder::where('id',$data['order_id'])->update(['car_id'=>$data['car_id'], 'car_no'=>$data['car_no']]);
                        // 修改库存占用时间的车辆
                        CarOccupyTime::where(['order_id'=>$data['order_id'],'start_time'=>$orderInfo['start_time'],'end_time'=>$orderInfo['end_time']])->update(['is_del'=>1,'delete_time'=>time()]);
                    }
                }
                //新增2024年1月26日15:06:40  等改为自动排车后这里要删了
//                if($data['car_id']){
//                    $occupy = [
//                        'car_id'=>$data['car_id'],
//                        'order_id'=>$data['order_id'],
//                        'occupy_type'=>'book',
//                        'start_time'=>$orderInfo['start_time'],
//                        'end_time'=>$orderInfo['end_time'],
//                        'remark'=>'用户预约占用',
//                        'add_time'=>time(),
//                    ];
//                    if(!CarOccupyTime::create($occupy)){
//                        throw new ValidateException('添加库存占用时间失败');
//                    }
//                }
                $title = '订单【'.CarOrder::where('id',$data['order_id'])->value('order_no').'】完成取车，车牌号【'.$data['car_no'].'】';
                BaseLogServices::addLog($data['order_id'],2,$title,$op_user_type,$op_user['id'],$op_user['user_name'],5);
            }else{ // 新增
                $insert['take_no'] = $this->getTakeNo();
                $insert['deposit_pay_time'] = $data['deposit_pay_time'];
                $insert['add_time'] = time();

                $take_id = CarOrderTake::insertGetId($insert);
                if($op_user_type == 2){
                    CarOrder::where('id',$data['order_id'])->update(['take_id'=>$take_id,'status'=>20]);
                }else{
                    CarOrder::where('id',$data['order_id'])->update(['take_id'=>$take_id]);
                }
                if($data['car_id']){
                    $occupy = [
                        'car_id'=>$data['car_id'],
                        'order_id'=>$data['order_id'],
                        'occupy_type'=>'book',
                        'start_time'=>$orderInfo['start_time'],
                        'end_time'=>$orderInfo['end_time'],
                        'remark'=>'用户预约占用',
                        'add_time'=>time(),
                    ];
                    if(!CarOccupyTime::create($occupy)){
                        throw new ValidateException('添加库存占用时间失败');
                    }
                }
            }
        });
        return '提交成功';
    }

    /**
     * 支付下单后，车辆库存占用
     * @param int $order_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function payOrderTake($order_id = 0,$op_user,$op_user_type){
        $orderInfo = CarOrder::where('id',$order_id)->find();
        $orderInfo = $orderInfo ? $orderInfo->toArray() : [];
        $carInfoServices = app()->make(CarInfoServices::class);
        $car_info = $carInfoServices->getCarInventory($orderInfo['type_id'],$orderInfo['start_time'],$orderInfo['end_time']);
        $car_list = $car_info['car_list'];
        if ($car_info['inventory']<=0){
            throw new ValidateException('当前选择车辆已无库存，请选择其他车型下单！');
//            return false;
        }
        $data = [
//            'car_id'=>$car_list[0]['id'],
//            'car_no'=>$car_list[0]['car_no'],
            'car_id'=>$orderInfo['car_id'],
            'car_no'=>$orderInfo['car_no'],
            'take_time'=>$orderInfo['start_time'],
            'take_pic_oil'=>'',
            'take_video'=>'',
            'take_injury_pic'=>'',
            'take_contract_pic'=>'',
            'old_type_id'=>0,
            'new_type_id'=>$orderInfo['type_id'],
            'order_id'=>$order_id,
            'integral_fee'=>0,
            'deposit_fee'=>0,
            'deposit_pay_time'=>0,
            'sign_post_time'=>0,
            'sign_notify_time'=>0,
            'take_km'=>''
        ];

        $this->accomplisTake($data,$op_user,$op_user_type);
        return true;
    }
}
